package com.itheima.service;

import com.itheima.dao.ContactDao;
import com.itheima.pojo.Contact;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

/**
 * @author slstart
 * @create 2021-05-23 19:22
 */
public class ContactService {

    public List<Contact> findAll() throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ContactDao mapper = sqlSession.getMapper(ContactDao.class);
        List<Contact> list = mapper.findAll();
        sqlSession.close();
        return list;
    }

    public boolean addContact(Contact contact) throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactDao mapper = sqlSession.getMapper(ContactDao.class);
        int i = mapper.add(contact);
        sqlSession.close();
        return i > 0;
    }

    public Contact findById(String id) throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        ContactDao mapper = sqlSession.getMapper(ContactDao.class);
        Contact contact = mapper.findById(id);
        sqlSession.close();
        return contact;
    }

    public boolean updateContact(Contact contact) throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactDao mapper = sqlSession.getMapper(ContactDao.class);
        int i = mapper.updateContact(contact);
        return i > 0;
    }

    public boolean deleteById(String id) throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlSession(true);
        ContactDao mapper = sqlSession.getMapper(ContactDao.class);
        int i = mapper.deleteContactById(id);
        return i>0;
    }
}
